<?php

	namespace app\home\controller;


	use think\Db;
	use think\Exception;
	use app\home\validate\OrderValidate;
	use app\home\model\OrderGoods;
	use app\home\model\Cart as cartModel;
	use app\home\model\Order as orderModel;

	class Order extends Base
	{
		public function submit () {

			$orderValidate = new  OrderValidate();
			$validateRes = $orderValidate->goSceneCheck('submit');
			if ($validateRes) {
				return error($validateRes);
			}

			$form = (int) $this->request->post('form');
			$openid = $this->member->openid;

			//获取购物车中默认选中的商品
			if ($form == 1) {
				$cartModel = new cartModel();
				$cart_list = $cartModel->field('id,goods_id,total,price')->where(['openid' => $openid, 'seleted' => 1, 'deletetime' => 0])->select();

				if (empty($cart_list)) {
					return error('选择购买的商品');
				}

				$price = 0;
				foreach ($cart_list as $cart) {
					$price += $cart->price * $cart->total;
				}

				$orderModel = new orderModel();
				$orderModel->openid = $openid;
				$orderModel->ordersn = $this->createSN();
				$orderModel->price = $price;
				$orderModel->address_id = intval($this->request->post('address_id'));
				$orderModel->createtime = time();
				$orderModel->save();
				$order_id = $orderModel->id;

				if (!$order_id) {
					return error('订单生成失败');
				}

				//插入订单商品
				foreach ($cart_list as $cart) {
					$orderGoodsModel = new OrderGoods();
					$orderGoodsModel->order_id = $order_id;
					$orderGoodsModel->goods_id = $cart->goods_id;
					$orderGoodsModel->total = $cart->total;
					$orderGoodsModel->createtime = time();
					$orderGoodsModel->save();

					if (!$orderGoodsModel->id) {
						return error('订单商品生成失败');
					}
				}

				//删除购物车
				$cartModel->where(['openid' => $openid, 'seleted' => 1, 'deletetime' => 0])->update(['deletetime' => time()]);

				return success(['order_id' => $order_id]);
			}
		}

		public function getOneOrder () {
			$orderValidate = new  OrderValidate();
			$validateRes = $orderValidate->goSceneCheck('getOneOrder');
			if ($validateRes) {
				return error($validateRes);
			}
			$order_id = intval($this->request->post('order_id'));
			$orderModel = new orderModel();
			$openid = $this->member->openid;
			$item = $orderModel->field('id,ordersn,price')->where(['openid' => $openid, 'id' => $order_id, 'deletetime' => 0])->find();
			if ($item) {
				return success($item);
			}

			return error('订单不存在或已删除');
		}

		public function getOrderList () {

			$openid = $this->member->openid;

			$orderModel = new orderModel();

			$list = $orderModel->with(['ordergoods', 'ordergoods.goods'])->where(['openid' => $openid, 'deletetime' => 0])->select();

			if ($list) {
				return success($list);
			}

			return error('暂无数据');
		}


		public function pay () {

			$orderValidate = new  OrderValidate();
			$validateRes = $orderValidate->goSceneCheck('pay');
			if ($validateRes) {
				return error($validateRes);
			}

			$type = trim($this->request->post('type'));
			$order_id = intval($this->request->post('order_id'));

			$orderModel = new orderModel();
			$item = $orderModel->where(["id" => $order_id, 'status' => 0, 'deletetime' => 0])->find();
			if (!$item) {
				return error('订单不存在或已支付');
			}

			if ($type == 'credit') {//余额支付
				$openid = $this->member->openid;
				$memberModel = new \app\home\model\Member();
				$member = $memberModel->where(['openid' => $openid, 'deletetime' => 0])->find();
				if ($member->credit < $item->price) {
					return error('余额不足');
				}
				Db::startTrans();
				try {
					$credit = $member->credit - $item->price;
					$member->credit = $credit;
					$row = $member->save();

					if ($row < 1) {
						throw new Exception('余额支付失败');
					}

					$item->status = 1;
					$row = $item->save();

					if ($row < 1) {
						throw new Exception('订单状态修改失败');
					}

					//修改商品数量
					$orderGoodsModel = new OrderGoods();
					$order_goods_list = $orderGoodsModel->field('id,goods_id,total')->find(['order_id' => $order_id, 'deletetime' => 0])->select();
					if ($order_goods_list) {
						foreach ($order_goods_list as $value) {
							$res = $this->updateStock($value->goods_id, $value->total);
							if ($res) {
								throw new Exception($res);
							}
						}
					}

					Db::commit();

					return error('订单支付成功', 1);
				} catch (Exception $e) {
					Db::rollback();

					return error($e->getMessage());
				}
			}
		}

		protected function createSN () {
			$ordersn = 'WXSN' . date('YmdHis', time()) . random(6, true);
			while (1) {
				$orderModel = new orderModel();
				$count = $orderModel->where('ordersn', $ordersn)->count('id');
				if ($count <= 0) {
					break;
				}
				$ordersn = 'WXSN' . date('YmdHis', time()) . random(6, true);
			}

			return $ordersn;
		}

		protected function updateStock ($goods_id, $num) {
			$goodsModel = new \app\home\model\Goods();
			$goods = $goodsModel->field('id,stock')->where(['id' => $goods_id])->find();
			if ($goods->stock < $num) {
				return $goods->name . ':数量不足';
			}
			$goods->stock -= $num;
			$row = $goods->save();
			if ($row < 1) {
				return '数量修改失败';
			}

			return false;
		}

	}
